package com.example.myapplication13_1;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private MediaPlayer mediaPlayer;
    private Button btnPlayPause;
    private Button btnStop;
    private boolean isPlaying = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化MediaPlayer，设置音频文件
        mediaPlayer = MediaPlayer.create(this, R.raw.testmusic1);

        // 获取按钮引用
        btnPlayPause = findViewById(R.id.btn_Start);
        btnStop = findViewById(R.id.btn_Stop);

        // 设置播放/暂停按钮点击事件
        btnPlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPlaying) {
                    // 如果正在播放，则暂停
                    mediaPlayer.pause();
                    btnPlayPause.setText("播放");
                    isPlaying = false;
                } else {
                    // 如果已暂停，则播放
                    mediaPlayer.start();
                    btnPlayPause.setText("暂停");
                    isPlaying = true;
                }
            }
        });

        // 设置停止按钮点击事件
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    try {
                        mediaPlayer.prepare();
                        mediaPlayer.seekTo(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    btnPlayPause.setText("播放");
                    isPlaying = false;
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}